<?php
declare(strict_types=1);

namespace app\controller\admin;

use app\BaseController;
use app\model\{CouponOrder, User, Merchant};
use think\facade\{Db, Log};
use think\Request;

class CouponOrderController extends BaseController
{
    /**
     * 获取订单列表
     */
    public function list(Request $request)
    {
        $where = [];
        
        // 游标ID
        $last_id = (int)$request->param('last_id', 0);
        if ($last_id > 0) {
            $where[] = ['id', '<', $last_id];
        }
        
        // 商家ID筛选
        if ($merchant_id = $request->param('merchant_id')) {
            $where[] = ['merchant_id', '=', $merchant_id];
        }
        
        // 业务类型 1快递 2滴滴打车 3花小猪 4美团 5饿了么 6淘宝 7京东 8拼多多 9抖音
        if ($business_type = $request->param('business_type')) {
            $where[] = ['business_type', '=', $business_type];
        }
        
        // 状态 0未支付 1已支付 2已取消
        if ($status = $request->param('status')) {
            $where[] = ['status', '=', $status];
        }
        
        // 时间范围筛选
        if ($start_time = $request->param('start_time')) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time = $request->param('end_time')) {
            $where[] = ['create_time', '<=', $end_time];
        }
        
        // 关键词搜索
        if ($keyword = $request->param('keyword')) {
            $where[] = ['order_no|title', 'like', "%{$keyword}%"];
        }
        
        // 每页条数
        $limit = (int)$request->param('limit', 15);
        
        $list = CouponOrder::where($where)
            ->with(['user', 'merchant'])
            ->order('id', 'desc')
            ->limit($limit + 1)  // 多查询一条用于判断是否有下一页
            ->select();
            
        $has_more = false;
        if (count($list) > $limit) {
            $has_more = true;
            $list = array_slice($list->toArray(), 0, $limit);
        } else {
            $list = $list->toArray();
        }
        
        // 获取下一页的游标ID
        $next_id = 0;
        if ($has_more && !empty($list)) {
            $next_id = end($list)['id'];
        }
            
        // 统计数据
        $stats = [
            'total_count' => CouponOrder::where($where)->count(),
            'total_amount' => CouponOrder::where($where)->sum('order_amount'),
            'merchant_profit' => CouponOrder::where($where)->sum('merchant_commission'),
            'platform_profit' => CouponOrder::where($where)->sum('platform_commission')
        ];
            
        return $this->success('获取成功', [
            'list' => $list,
            'has_more' => $has_more,
            'next_id' => $next_id,
            'stats' => $stats
        ]);
    }
    
    /**
     * 获取订单详情
     */
    public function detail($id)
    {
        $order = CouponOrder::with(['user', 'merchant'])->find($id);
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        return $this->success('获取成功', $order);
    }
   
    
    /**
     * 导出订单列表
     */
    public function export(Request $request)
    {
        $list = CouponOrder::with(['user', 'merchant'])->select();
        
        // 设置 CSV 头
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment;filename="订单列表.csv"');
        
        // 打开输出流
        $fp = fopen('php://output', 'w');
        
        // 写入表头
        fputcsv($fp, [
            '订单号', '商家名称', '用户名称', '订单金额', 
            '订单状态', '创建时间'
        ]);
        
        // 写入数据
        foreach ($list as $order) {
            fputcsv($fp, [
                $order->order_no,
                $order->merchant->merchant_name,
                $order->user->real_name,
                $order->fee_actual,
                $this->getOrderStatus($order->order_status),
                $order->create_time
            ]);
        }
        
        fclose($fp);
        exit;
    }
    
    /**
     * 获取订单状态文本
     */
    protected function getOrderStatus($status)
    {
        $map = [
            0 => '待支付',
            1 => '待揽收',
            2 => '运输中',
            3 => '已完成',
            98 => '已取消',
            99 => '已关闭'
        ];
        return $map[$status] ?? '';
    }
    
    /**
     * 获取支付状态文本
     */
    protected function getPayStatus($status)
    {
        $map = [
            0 => '未支付',
            1 => '已支付',
            2 => '已退款'
        ];
        return $map[$status] ?? '';
    }
    
    /**
     * 处理退款
     */
    protected function handleRefund($order)
    {
        // 根据支付方式退款
        if ($order->payment_method == 'wechat') {
            $wechatService = new WechatService($order->merchant_id);
            $result = $wechatService->refund([
                'out_trade_no' => $order->order_no,
                'total_fee' => $order->fee_actual * 100,
                'refund_fee' => $order->fee_actual * 100,
                'refund_desc' => '订单取消退款'
            ]);
        } else if ($order->payment_method == 'alipay') {
            $alipayService = new AlipayService($order->merchant_id);
            $result = $alipayService->refund([
                'out_trade_no' => $order->order_no,
                'refund_amount' => $order->fee_actual,
                'refund_desc' => '订单取消退款'
            ]);
        }
        
        if (!$result) {
            throw new \Exception('退款失败');
        }
        
        // 更新订单退款状态
        $order->save([
            'refund_status' => 2, // 已退款
            'refund_time' => date('Y-m-d H:i:s'),
            'refund_amount' => $order->fee_actual,
            'refund_remark' => '订单取消退款'
        ]);
    }
} 